const express = require('express')
const {
  insertCartList,
  queryCartListByUserId,
  deleteCartByGoodsInfoIdAndUserId,
  deleteCartAllByUserId
} = require('../mysql/cart')
const { queryGoodsInfoByGoodsInfoId } = require('../mysql/goodsInfo')
const Result = require('../result/result')
const { NO_PERMISSION } = require('../result/reponseState')

const router = express.Router()

router.get('', (req, res) => {
  const user_id = req.query
  queryCartListByUserId(user_id).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})
router.get('/search', (req, res) => {
  const goodsInfo_ids = req.query
  queryGoodsInfoByGoodsInfoId(goodsInfo_ids).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})
router.put('/add', (req, res) => {
  const cartList = req.body
  insertCartList(cartList).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})
router.delete('/delete', (req, res) => {
  const { goodsInfo_id, user_id } = req.body
  deleteCartByGoodsInfoIdAndUserId(Number(goodsInfo_id), Number(user_id)).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})
router.delete('/deleteAll', (req, res) => {
  const { user_id } = req.body
  deleteCartAllByUserId(Number(user_id)).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})

module.exports = router